<?php
class sfWidgetFormSchemaFormatterJfPD extends sfWidgetFormSchemaFormatter
{
  protected
    $rowFormat = '<div class="%fieldname%%row_class% formSet" data-role="fieldcontain">%label% %field% %error% %help% %hidden_fields%</div>',
    $errorListFormatInARow = '<span class="error">%errors%</span>',
    $errorRowFormatInARow = '<span class="error">%error%</span>',
    $namedErrorRowFormatInARow = '<span class="error"><strong>%name%:</strong> %error%</span>',
    $helpFormat = '<small class="help">%help%</small>';

  public function formatRow($label, $field, $errors = array(), $help = '', $hiddenFields = null)
  {
  	$originalRowFormat = $this->rowFormat;
  	if (strpos($field, 'type="radio"') || strpos($field, 'type="checkbox"')) {
  		$isCheckboxList = strpos($field, 'checkbox_list') !== false;
  		$field = str_replace(array('<ul class="radio_list">', '<ul class="checkbox_list">', '</ul>', '<li>', '</li>'), array('', '', '', '', ''), $field);
  		
  		//change order of input and label tags
  		$pattern = '#(<input\b[^>]*/>)(.*?)(<label\b[^>]*>)(.*?)(</label>)$#';
			$replacement = '$3$4$5$1';
  		$rows = explode("\n", $field);
  		foreach($rows as $index => $row) {
				$rows[$index] = preg_replace($pattern, $replacement, $row);
  		}
  		$field = implode("\n", $rows);
  		
  		if ($isCheckboxList) {
	  		$label = substr($label, strpos($label, '>')+1);
	  		$label = substr($label, 0, strpos($label, '<'));
	  		
	  		$field = '<fieldset data-role="controlgroup"><legend>'.$label.'</legend>'.$field.'</fieldset>';
	  		$label = null;
  		}
  		else {
  			$field = '<div data-role="controlgroup">'.$field.'</div>';
  		}
  	}
  	
    $row = parent::formatRow(
      $label,
      $field,
      $errors,
      $help,
      $hiddenFields
    );
    
    $this->rowFormat = $originalRowFormat;
    
    $fieldName = substr($label, strpos($label, ' for="')+6);
    $fieldName = substr($fieldName, 0, strpos($fieldName, '"'));

    return strtr($row, array(
      '%row_class%' => (count($errors) > 0) ? ' error' : '',
      '%fieldname%' => $fieldName,
      ' type="' => (count($errors) > 0) ? ' class="error" type="' : ' type="',
    ));
  }

}